package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 路由工作模式
 */
public class Producer03_Routing {
    // EMAIL队列
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    // SMS队列
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    // 交换机
    private static final String EXCHANGE_ROUTING_INFORM = "exchange_routing_inform";
    // 交换机key
    public static final String ROUTING_KEY_EMAIL = "email";
    public static final String ROUTING_KEY_SMS = "sms";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 创建连接
            connection = connectionFactory.newConnection();
            // 创建对话通道
            Channel channel = connection.createChannel();
            // 设置通道目的地
            channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null);
            channel.queueDeclare(QUEUE_INFORM_SMS, true, false, false, null);
            // 声明交换机
            /**
             * exchange: 交换机的名字
             * type: 交换机的类型
             *  FANOUT : 对应publish/subscribe工作模式
             *  DIRECT : 对应Routing工作模式
             *  TOPIC : 对应Topic工作模式
             *  HEADERS : 对应headers工作模式
             */
            channel.exchangeDeclare(EXCHANGE_ROUTING_INFORM, BuiltinExchangeType.DIRECT);
            // 绑定交换机和路由key
            channel.queueBind(QUEUE_INFORM_EMAIL, EXCHANGE_ROUTING_INFORM, ROUTING_KEY_EMAIL);
            channel.queueBind(QUEUE_INFORM_SMS, EXCHANGE_ROUTING_INFORM, ROUTING_KEY_SMS);
            // 发送消息
            for (int i = 0; i < 5; i++) {
                // 发送消息的时候指定routing_key
                // 将偶数发给sms的routing
                // 将奇数发给email的routing
                if (i % 2 == 0) {
                    String s = "发送偶数" + i;
                    channel.basicPublish(EXCHANGE_ROUTING_INFORM, ROUTING_KEY_SMS, null, s.getBytes());
                } else {
                    String s = "发送奇数" + i;
                    channel.basicPublish(EXCHANGE_ROUTING_INFORM, ROUTING_KEY_EMAIL, null, s.getBytes());
                }
            }
            System.out.println("发送完成");
            channel.close();
            connection.close();
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
